package com.company.ljh.easy;
/**
 * 从上到下按层打印二叉树，同一层的节点按从左到右的顺序打印，每一层打印到一行。
 */

import com.company.ljh.utils.TreeNode;

import java.util.ArrayList;
import java.util.List;

/**
 * @description:
 * @projectName:leet_code
 * @see:com.company.ljh.easy
 * @author:ljh
 * @createTime:2022/6/7 14:13
 * @version:1.0
 */
public class 从上到下打印二叉树II {
    public List<List<Integer>> levelOrder(TreeNode root) {

        List<List<Integer>> result = new ArrayList();
        if(root == null){
            return result;
        }
        int i =0;
        listTreeNode(root,i,result);
        return result;
    }
    private void listTreeNode(TreeNode root, int i, List<List<Integer>> result){
        List<Integer> list;
        if(result.size() < i+1){
            list = new ArrayList<Integer>();
            result.add(list);
        }else{
            list = result.get(i);
        }
        list.add(root.val);
        if(root.left != null){
            listTreeNode(root.left,i+1,result);
        }
        if(root.right != null){
            listTreeNode(root.right,i+1,result);
        }
    }
}
